package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {


    /**
     * 过滤器执行的逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取当前的请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 判断请求的路径是否需要鉴权
        String path = request.getURI().getPath();
        // 这里判断路径中是否包含/login
        if (path.contains("/login")) {
            // 不需要鉴权的话直接放行请求--路由到网关后面的微服务
            return chain.filter(exchange);
        }
        // 获取请求头
        String token = request.getHeaders().getFirst("token");
        // 如果需要鉴权,判断是否在请求头中携带token
        if (!StringUtils.isEmpty(token)) {
            // 有token,需要通过JWT工具验证token是否有效
            try {
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                int result = AppJwtUtil.verifyToken(claimsBody);
                if (result == -1 || result == 0) {
                    // token有效,从token中解析自定义的用户信息,这里指userId
                    Object userId = claimsBody.get("userId");
                    // 将用户id放入到请求头中转发给后面的微服务(方便后面的微服务判断当前登录的用户)
                    request.mutate().header("userId", userId.toString());
                    return chain.filter(exchange);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
        // 如果没有token,提示401未授权
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器执行的顺序,数值越小,优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
